<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/29 0029
 * Time: 下午 3:17
 */

namespace Repositories;

use EasyWeChat\Foundation\Application as Weichat;

class WeiChatRep
{
    protected $appId ;          // AppID
    protected $secret;          // AppSecret
    protected $token;           // Token
    protected $aesKey;          // EncodingAESKey，安全模式下请一定要填写！！！
    protected $scopes;          //认证类型
    protected $callback;        //回调地址
    protected $options;         //配置数组
    protected $wechatManager;
    protected $mchId;           //商户id

    public function __construct($mchId)
    {
        $this->mchId = $mchId;
        if($mchId == -1){
            $this->appId  = 'wx18f8db9fbd084c5e';
            $this->secret = '1dcd6c7d4d8093dd60b14ba8d38a092b';
        }else{
            $this->appId  = 'wx18f8db9fbd084c5e';
            $this->secret = '1dcd6c7d4d8093dd60b14ba8d38a092b';
        }
        $this->initOptions();
    }

    public function setScopes($scopes = 'snsapi_base'){
        $this->scopes = $scopes;
        return $this;
    }

    public function initOptions(){

        $this->options = [
            'app_id' => $this->appId,
            'secret' => $this->secret,
            'token' => $this->token,
            'aes_key' => $this->aesKey,
            'oauth' => [
                'scopes' => [$this->scopes],
                'callback' => $this->callback,
            ]
        ];
        return $this;
    }

    public function setCallback($callback){
        $this->callback = $callback;
        $this->initOptions();
        return $this;
    }

    public function toAuth(){
        $this->wechatManager  = new Weichat($this->options);
        $oauth = $this->wechatManager->oauth->with(['component_appidw'=>'dsfsdfsdfsdf']);
        $oauth->redirect()->send();
    }

    public function authReturn($qrcode){
        $this->initOptions();
        $this->wechatManager  = new Weichat($this->options);
        $oauth = $this->wechatManager->oauth;
        $user = $oauth->user();
        $sessionType = 'platformUserInfo';
        $redirect = U('index',['qrcode'=>$qrcode]);
        switch ($this->mchId){
            case -1 :break;
            default : $sessionType = 'userInfo_'.$this->mchId;
        }
        session($sessionType,$user->toArray());
        redirect($redirect);
    }


}